package View;

import java.util.ArrayList;
import java.util.Scanner;


import Controller.UserController;
import Helper.Helper;
import Model.*;

public class UserIndex {
    public static void index(String username){
        Helper.clear();
        System.out.printf("*-----[ 买家 | %5s ]-----*\n\n", username);

        System.out.println("\t 1. 浏览商品");
        System.out.println("\t 2. 搜索商品");
        System.out.println("\t 3. 查看订单\n");
        System.out.println("\t 4. 收藏夹");

        System.out.println("\t 5. 注销");

        System.out.println("*---------------------------*");
    }

    public static void listProducts(){
        Helper.listProducts();

        buy();
    }

    public static void searchProduct(){
        Helper.searchProduct();

        buy();
    }

    public static void listOrders(){
        System.out.println("[ 我的订单 ]\n");

        System.out.println("订单编号 | 商品编号 | 商品名称 | 单价 | 数量 | 总价 | 状态");
        ArrayList<Order> orders = UserController.listOrders();

        for( Order item : orders ){
            String status = "";
            switch (item.status) {
                case 0:
                    status = "未发货";
                    break;
                case 1:
                    status = "已发货";
                    break;
                case 2:
                    status = "交易完毕";
                    break;
            }
            String fstr = "%4d %4d  %6s  %2.1f %4d %2.1f %4s\n";
            System.out.printf(fstr,item.id,item.productId,item.name,item.productPrice,item.amount,item.price,status);
        }

        Helper.waitter();
    }

    private static void buy(){
        if( Helper.brancher("是否购买？", false) ){
            Scanner scanner = new Scanner(System.in);

            int id,amount;
            String temp;
            do{
                System.out.print("请输入商品编号: ");
                temp = scanner.next();
            }while( !temp.matches("[0-9]+") || Integer.parseInt(temp)<=0 );
            id = Integer.parseInt(temp);

            ProductM productM = new ProductM();
            ArrayList<Product> p = productM.find(id);

            if( p.size() == 0 ){
                System.err.println("不存在编号为"+id+"的商品！");
            } else {
                System.out.println("正在购买： 【 "+p.get(0).name+" 】");

                do{
                    System.out.print("请输入购买数量: ");
                    temp = scanner.next();
                }while( !temp.matches("[0-9]+") || Integer.parseInt(temp)<=0 );
                amount = Integer.parseInt(temp);

                float price = p.get(0).price * amount;

                if( !Helper.brancher("确定？", true) ){
                    return;
                }

                if( UserController.buy(id, amount, price) ){
                    System.out.println("购买成功！");
                }else{
                    System.err.println("购买失败！");
                }
            }

            Helper.waitter();
        }
    }
}
